<!-- 搜索表单 -->
<template>
  <a-card :bordered="false">
    <!-- 搜索表单 -->
    <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
      <a-row>
        <a-col :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-item label="名称">
            <a-auto-complete v-model:value="applyCustomsWhere.customer" :options="customerOptions" placeholder="请输入名称"
              @select="customer_onSelect2" @search="customer_onSearch" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-item label="提单号">
            <a-input v-model:value.trim="applyCustomsWhere.billOfLading" 
              placeholder="请输入提单号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-item label="状态">
            <a-select v-model:value="applyCustomsWhere.state" placeholder="请选择" allow-clear>
              <a-select-option value="">全部订单</a-select-option>
              <a-select-option value="未关联">未关联</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" :xs="24" >
          <a-form-item :wrapper-col="{ span: 24 }">
            <em></em>
            <a-space>
              <a-button type="primary" @click="applyCustomsReload">查询</a-button>
              <a-button @click="applyCustomsReset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 表格 -->
    <ele-pro-table ref="applyCustomsTableRef" row-key="id" :columns="columns"
      @update:selection="applyCustomsTableOnSelectionChange" :customRow="applyCustomsTableRowClick"
      v-model:current="applyCustomsCurrent" :datasource="datasource" :scroll="{ x: 1000 }">
      <template #toolbar>
        <a-space>
          <a-button type="primary" @click="applyCustomsOpenEdit()" v-any-permission="['order:applyCustoms:save']">
            <template #icon>
              <plus-outlined />
            </template>
            <span>下单</span>
          </a-button>
          <a-button @click="containOceanApplyBtn()" style="color: #4e72b8;" >
            <template #icon>
              <plus-outlined />
            </template>
            <span>报关关联</span>
          </a-button>
          <div v-if="applyCustomsCurrent.billOfLading != ''">
            <a-tag color="purple" v-if="applyCustomsCurrent.containbillId != 0 && applyCustomsCurrent.containbillId != null">拖车</a-tag>
            <a-tag color="cyan" v-if="applyCustomsCurrent.oceanId != 0 && applyCustomsCurrent.oceanId != null">海运</a-tag>
          </div>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'annex'">
          <template v-if="record.annex != '' && record.annex != null && record.annex.length>3">
            <template v-for="(item2, index2) in JSON.parse(record.annex)" :key="index2">
            <!-- <router-link :to="item2.url" @click.stop="" target="_blank">
                  {{ item2.name }}</router-link> -->
              <!-- <div><a :href="item2.url" target="_blank">{{ item2.name }}</a></div> -->
              <div class="annex" @click="openFile(item2.url)">{{ index2 + 1 }}. {{ item2.name }}</div>
            </template>
          </template>
          <template v-else>
            <div></div>
          </template>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="applyCustomsOpenEdit(record)" v-any-permission="['order:applyCustoms:update']">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除此项吗？" @confirm="applyCustomsRemove(record)">
              <a class="ele-text-danger" v-any-permission="['order:applyCustoms:remove']">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </a-card>
  <!-- 报关添加、修改弹窗 -->
  <ele-modal :width="560" v-model:visible="applyCustomsVisible_modal" :confirm-loading="loading"
    :title="applyCustomsIsUpdate ? '修改报关' : '新建报关'" :body-style="{ paddingBottom: '8px' }" @ok="applyCustomsSave"
    :maskClosable="false">
    <a-form ref="applyCustomsFormRef" :model="applyCustomsForm" :rules="applyCustomsRules"
      :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
      <a-form-item label="客户名称" name="customer">
        <a-auto-complete v-model:value="applyCustomsForm.customer_val" :options="customerOptions" placeholder="请输入客户名称"
          @select="customer_onSelect" @search="customer_onSearch" @blur="customer_blur" allow-clear />
      </a-form-item>
      <a-form-item label="报关代理" name="customsAgent">
        <a-auto-complete v-model:value="applyCustomsForm.customsAgent_val" :options="customsAgentOptions"
          placeholder="请输入报关代理" @select="customsAgent_onSelect" @search="customsAgent_onSearch" @blur="customsAgent_blur"
          allow-clear />
      </a-form-item>
      <a-form-item label="报关日期" name="customsDate">
        <a-date-picker v-model:value="applyCustomsForm.customsDate" valueFormat="YYYY-MM-DD" placeholder="请输入报关日期"
          class="ele-fluid" allow-clear />
      </a-form-item>
      <a-form-item label="报关地" name="customsPlace">
        <a-select v-model:value="applyCustomsForm.customsPlace" show-search placeholder="请输入报关地"
          :options="customsPlace_options" :filter-option="customsPlace_filter"></a-select>
      </a-form-item>
      <a-form-item label="提单号" name="billOfLading">
        <a-input allow-clear :maxlength="200" placeholder="请输入提单号" v-model:value="applyCustomsForm.billOfLading"
          autocomplete="off" />
      </a-form-item>
      <a-form-item label="附件" name="annex">
        <a-upload-dragger v-model:file-list="applyCustomsForm.annexFilelist" 
        @remove="annexUploadFilesRemove"
        :customRequest="annexUploadFiles"
          :multiple="true">
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">Click or drag file to this area to upload</p>
          <p class="ant-upload-hint">
            Support for a single or bulk upload. Strictly prohibit from uploading company data or other
            band files
          </p>
        </a-upload-dragger>
      </a-form-item>
    </a-form>
  </ele-modal>
    <!-- 拖车海运报关 关联表 弹窗 -->
    <ele-modal :width="1300"  v-model:visible="containOceanApply_modal" :confirm-loading="loading" title="拖车海运报关 关联表"
    :body-style="{ paddingBottom: '8px' }" :maskClosable="false" :move-out="true" footer=""
    :resizable="false" position="center">
    <ContainerOceanApply ref="containOceanApplyComp"></ContainerOceanApply>
  </ele-modal>
</template>

<script setup>
import { ref, reactive,watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';

import { listSettings } from '@/api/order/settings';
import { listCustomersSel } from '@/api/order/customer';
import { pageApplyCustoms, removeApplyCustoms, addApplyCustoms, updateApplyCustoms } from '@/api/order/applyCustoms';

import { API_BASE_URL } from '@/config/setting';
import { fileUpload } from '@/api/file';

import ContainerOceanApply from '@/views/order/containerBill/components/containerOceanApply.vue';

function openFile(op) {
  // 打开新窗口
  window.open(API_BASE_URL + '/file/' + op, '_blank');
}
// 表格实例
const applyCustomsTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (applyCustomsTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '附件',
    dataIndex: 'annex',
    key: 'annex',
    // sorter: true
  },
  {
    title: '客户名称',
    dataIndex: 'customer',
    key: 'customer',
    // sorter: true
  },
  {
    title: '报关代理',
    dataIndex: 'customsAgent',
    key: 'customsAgent',
    // sorter: true
  },
  {
    title: '报关日期',
    dataIndex: 'customsDate',
    key: 'customsDate',
    // sorter: true
  },
  {
    title: '报关地',
    dataIndex: 'customsPlace',
    key: 'customsPlace',
    // sorter: true
  },
  {
    title: '提单号',
    dataIndex: 'billOfLading',
    key: 'billOfLading',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: applyCustomsWhere, resetFields } = useFormData({
  username: '',
  sex: undefined,
});

// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  return pageApplyCustoms({ ...where, ...orders, page, limit });
};

/* 搜索 */
const applyCustomsReload = () => {
  applyCustomsTableRef?.value?.reload({ page: 1, where: applyCustomsWhere });
};
const applyCustomsReload2 = () => {
  applyCustomsTableRef?.value?.reload();
};


let where_timeout = 0
watch(() => applyCustomsWhere, (val) => {
  clearTimeout(where_timeout)
  where_timeout = setTimeout(() => {
    applyCustomsReload()
  }, TIME_OUT);
},
{ deep: true }
)

/*  重置 */
const applyCustomsReset = () => {
  resetFields();
  applyCustomsReload();
};

let applyCustomsTableRowClick = (record, index) => {
  return {
    onClick: (event) => {
      applyCustomsCurrent.value = record
      sendApplySelect()
    },
  }
}
let applyCustomsTableOnSelectionChange = (current_options) => {
  applyCustomsCurrent.value = current_options[0];
  sendApplySelect()
};
let sendApplySelect = () => {
  // applyCustomsReload()
  // //applyCustomsFeeComp
  emit('applyCustomsIdSelect', {
    'applyCustomsId': applyCustomsCurrent.value.id,
    'invoice': {
      'company': applyCustomsCurrent.value.customer,
      'customsAgent': applyCustomsCurrent.value.customsAgent,
    }
  });
}
const emit = defineEmits(['applyCustomsIdSelect'])

/* 删除单个 */
const applyCustomsRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeApplyCustoms(record.id).then((msg) => {
    hide();
    message.success(msg);
    applyCustomsReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const applyCustomsCurrent = ref({});

// 弹窗是否打开
const applyCustomsVisible_modal = ref(false);

// 弹窗是否打开
const containOceanApply_modal = ref(false);
// 是否是修改
const applyCustomsIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const applyCustomsFormRef = ref(null);

// 表单数据
const { form: applyCustomsForm, resetFields: applyCustomsResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  annex: '',
});

// 表单验证规则
const applyCustomsRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});


let containOceanApplyComp = ref(null)
const containOceanApplyBtn = () => {
  containOceanApply_modal.value = true;
  setTimeout(() => {
    // containerBillCurrent.value.son_type = 'containerBill'
  containOceanApplyComp.value.removeContaiOceanApplyFormData()
  // containOceanApplyComp.value.onContainerBillSelect(containerBillCurrent.value)
  }, 1000);
}

//防止重复刷新
//客户 下拉列表
const customerOptions = ref([]);
let customer_m_timeout = 0
const customer_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '货代' }).then(msg => {
      customerOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const customer_onSelect = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  applyCustomsForm.customer_val = option2.label
  applyCustomsForm.customer = option2.label
  applyCustomsForm.customerId = option2.value
};
const customer_blur = () => {
  applyCustomsForm.customer_val = applyCustomsForm.customer
};
//搜索客户条件
const customer_onSelect2 = (value2, option2) => {
  // let a = customerOptions.value.find((item)=> {return item.value=value})
  applyCustomsWhere.customer = option2.label
};
//报关代理 下拉列表
const customsAgentOptions = ref([]);
const customsAgent_onSearch = searchText => {
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '报关行' }).then(msg => {
      customsAgentOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
const customsAgent_onSelect = (value2, option2) => {
  // let a = customsAgentOptions.value.find((item)=> {return item.value=value})
  applyCustomsForm.customsAgent_val = option2.label
  applyCustomsForm.customsAgent = option2.label
  applyCustomsForm.customsAgentId = option2.value
};
const customsAgent_blur = () => {
  applyCustomsForm.customsAgent_val = applyCustomsForm.customer
};

//报关地 下拉
let customsPlace_options = ref([])
listSettings({ 'typeM': 'applyLand' }).then(msg => {
  customsPlace_options.value = msg
}).catch((e) => {
})
const customsPlace_filter = (input, option) => {
  // return (option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.pinyin.toLowerCase().indexOf(input.toLowerCase()) >= 0);
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
//附件上传
function annexUploadFiles(info) {
  //开始真正上传
  //上传接口
  //调用公共上传方法
  fileUpload({ 'file': info.file, 'path2': 'chf_apply' }).then((msg) => {
    const upload_file_list_tmp_arr = {}
    upload_file_list_tmp_arr['uid'] = info.file.uid
    upload_file_list_tmp_arr['name'] = info.file.name
    upload_file_list_tmp_arr['status'] = 'done'
    upload_file_list_tmp_arr['url'] = msg.data.path + "?path2=chf_apply"
    let arr = (applyCustomsForm.annex == '' || applyCustomsForm.annex == null) ? [] : JSON.parse(applyCustomsForm.annex)
    arr.push(upload_file_list_tmp_arr)
    applyCustomsForm.annex = JSON.stringify(arr)
    applyCustomsForm.annexFilelist == undefined || applyCustomsForm.annexFilelist.map(element => {
      element.status = 'done'
      element.url = API_BASE_URL + '/file/' + element.url
    })
    message.success('上传成功');

  }).catch((e) => {
    message.error(e.message);
  });
}
let annexUploadFilesRemove = info => {
  let arr = JSON.parse(applyCustomsForm.annex)
  arr.splice(arr.findIndex(item => item.uid == info.uid), 1)
  applyCustomsForm.annex = JSON.stringify(arr)
}

const fileUploadOpenForm = (record) => {
  applyCustomsForm.annexFilelist = []
  if (record != undefined) {
    if (record.annex != '') {
      applyCustomsForm.annexFilelist = [...JSON.parse(record.annex)]
    }
  }
}
/* 打开编辑弹窗 */
const applyCustomsOpenEdit = (record) => {
  applyCustomsResetFormFields();
  applyCustomsFormRef.value?.clearValidate();
  applyCustomsCurrent.value = record?? {};
  applyCustomsVisible_modal.value = true;
  Object.assign(applyCustomsForm, record ?? {});
  applyCustomsIsUpdate.value = !!record;
  applyCustomsForm.customer_val = ''
  applyCustomsForm.customsAgent_val = ''
  if (record != undefined) {
    applyCustomsForm.customer_val = record.customer
    applyCustomsForm.customsAgent_val = record.customsAgent
  }
  fileUploadOpenForm(record)
};

/* 保存编辑 */
const applyCustomsSave = () => {
  if (!applyCustomsFormRef.value) {
    return;
  }
  applyCustomsFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = applyCustomsIsUpdate.value ? updateApplyCustoms : addApplyCustoms;
    saveOrUpdate(applyCustomsForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      applyCustomsVisible_modal.value = false;
      applyCustomsReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<style lang="less" scoped>
.annex {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;

  cursor: pointer;
  color: #426ab3;
}</style>
